#!/usr/bin/perl -w
use strict;
use Getopt::Long;

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Usage

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

my $usage = <<'USAGE';

USAGE:

    extract_table_from_pg_dump.pl
                --table_name "accessions"
				dump.file
				[--help]
	
	extracts data from pg_dump for a particular table
		regular expression
	
	Prints to STDOUT
	
USAGE


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Get options

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
# mandatory
my $table_name;

# optional parameters
my $help;
GetOptions(
			'table_name|t=s'				=> \$table_name,
			'help'		  		 			=> \$help);

die $usage if ($help);
die "\nError:\n\tTable name missing\n" .$usage unless (defined $table_name);

print STDERR "\n\tFinding Start of table...\n\t[";
my $dot_represents = 50000;
my $line_cnt;

OUTER:
{
	while (<>)
	{
		if (!(++$line_cnt % $dot_represents))
		{
			print STDERR "\n\t" if (($line_cnt / $dot_represents) % 50 == 0);
			print STDERR '.' ;
		}
		if (/^COPY "$table_name" FROM stdin;/)
		{
			print STDERR "]\n\tPrinting table...\n\t[";
			$line_cnt = 0;
			print;
			last OUTER;
		}
	}
	print STDERR "\nError:\n\tTable $table_name not found.\n";
	exit;
}

$line_cnt = 0;
# inside loop
OUTER:
{
	while (<>)
	{
		if (!(++$line_cnt % $dot_represents))
		{
			print STDERR "\n\t" if (($line_cnt / $dot_represents) % 50 == 0);
			print STDERR '.' ;
		}
		print;
		if (/^\\\./)
		{
			print STDERR "]\n";
			last OUTER ;
		}
	}
   	print "\nError:\n\tEnd of Table $table_name '\.' not found.\n";
}


